package com.kbplus.demo.data.permission.config;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.kbplus.demo.data.permission.service.ConcurrentUserService;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author chenyiyin
 * @date 2021/10/26 15:08
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        JSONObject concurrentUser = ConcurrentUserService.concurrentUser();
        this.strictInsertFill(metaObject, "tenantId", String.class, concurrentUser.getStr("tenantId"));
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "createUser", String.class,concurrentUser.getStr("id"));
        this.strictInsertFill(metaObject, "createUsername", String.class,concurrentUser.getStr("name"));
        JSONArray postIds = concurrentUser.getJSONArray("postIds");
        this.strictInsertFill(metaObject, "createUserPostId", String.class,postIds.join(","));
        this.strictInsertFill(metaObject, "createUserOrganizationId", String.class,concurrentUser.getStr("organizationId"));
        this.strictInsertFill(metaObject, "lastModifyUser", String.class,concurrentUser.getStr("id"));
        this.strictInsertFill(metaObject, "lastModifyUsername", String.class,concurrentUser.getStr("name"));
        this.strictInsertFill(metaObject, "lastModifyTime", Date.class, new Date());

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        JSONObject concurrentUser = ConcurrentUserService.concurrentUser();
        this.strictUpdateFill(metaObject, "lastModifyUser", String.class, concurrentUser.getStr("id"));
        this.strictUpdateFill(metaObject, "lastModifyTime", Date.class, new Date());
        this.strictUpdateFill(metaObject, "lastModifyUsername", String.class, concurrentUser.getStr("name"));

    }
}
